import { MinusCircleTwoTone } from '@ant-design/icons'
import { Button, Dropdown, Menu, Modal, Popconfirm, Typography } from 'antd'
import { Fragment, useCallback, useEffect, useRef, useState } from 'react'
import { message } from '@hs-admin/utils'
import { deleteScopeDetailItem, deleteSubCommonScopeList, getScopeDetailList, getSubCommonScopeList } from '@/api/shoppingCart.ts'
import { commonModalStyle } from '@/views/ShoppingCart/components/CommonEditModal.tsx'
import useEditIndustryScope from '@/views/ShoppingCart/components/useEditIndustryScope.tsx'
import useEditAreaScope from '@/views/ShoppingCart/components/useEditAreaScope.tsx'
import useEditParkScope from '@/views/ShoppingCart/components/useEditParkScope.tsx'

const { Paragraph } = Typography

/** areaLevel的值
 * 1：省
 * 2：省、市
 * 3：省、市、区
 */
const commonKinds = [
  { label: '产业范围', key: 'industry' },
  { label: '区域范围', nameKey: '区', key: 'area', areaLevel: 3 },
  { label: '园区范围', key: 'park' },
  { label: '企业白名单范围', key: 'company_list' }
] as const
// 获取整体范围
const getTheCommonKind = (item: { key: string; dimension_name: string }) => {
  const theItem = commonKinds.find((it) => it.key === item.key)
  if (theItem) {
    if (theItem.nameKey && theItem.nameKey !== item.dimension_name) {
      return null
    }
    return theItem
  }
  return null
}

const specialKinds = [
  { label: '区域范围', nameKey: '市', key: 'area', areaLevel: 2, maybeName: false },
  { label: '区域范围', nameKey: '省', key: 'area', areaLevel: 1, maybeName: false },
  { label: '时间范围', key: 'time', maybeName: true },
  { label: '聚合范围', key: 'polymerize', maybeName: true }
] as const
// 获取非整体范围
const getTheSpecialKind = (item: { key: string; dimension_name: string }) => {
  const theItem = specialKinds.find((it) => it.key === item.key)
  if (theItem) {
    if (theItem.nameKey && theItem.nameKey !== item.dimension_name) {
      return null
    }
    if (theItem.maybeName) {
      return {
        ...theItem,
        label: item.dimension_name
      }
    }
    return theItem
  }
  return null
}
// 获取某一子项支持的范围是那种范围
const getTheKind = (item: any) => {
  const commonKind = getTheCommonKind(item)
  if (commonKind) {
    return {
      isCommon: true,
      kind: commonKind
    }
  }
  const specialKind = getTheSpecialKind(item)
  if (specialKind) {
    return {
      isCommon: false,
      kind: specialKind
    }
  }
  throw '未知类型'
}

// 获取所有选择了的整体范围的key
const getCommonKeys = (commonScopes: Array<any>) =>
  commonScopes
    .map(getTheCommonKind)
    .filter((it) => it)
    .map((it) => it!.key)

// 是否支持整体范围,特例是要处理地区范围省市区(好恶心🤮),areaLevel需要遍历整体范围的所有地区范围的所有地区code,查看00,0000支持程度
const ifSpecialItemSupportCommonScope = (commonKeys: Array<string>, specialFields: Array<any>, areaLevel?: number) => {
  const finalFields = specialFields.map(getTheKind)
  if (!commonKeys.includes('area')) {
    const finalKeys = finalFields.filter((it) => it.isCommon).map((it) => it.kind.key)
    return commonKeys.every((it) => finalKeys.includes(it))
  }
  if (!areaLevel) {
    throw '整体范围中选了区域，必需areaLevel'
  }
  const theArea = finalFields.find((it) => it.kind.key === 'area')
  if (!theArea) {
    // 此时整体范围选择了区域，但该项直接不支持任何区域范围，所以返回false
    return false
  } else {
    const level = (theArea.kind as { areaLevel: number }).areaLevel
    return level >= areaLevel
  }
}

// type CommonKindType = (typeof commonKinds)[number]['key']

const subCommonItems = [
  {
    key: 'industry',
    label: '产业范围'
  },
  {
    key: 'area',
    label: '区域范围'
  },
  {
    key: 'park',
    label: '园区范围'
  }
] as const
type SubType = (typeof subCommonItems)[number]['key']

console.log(getCommonKeys, ifSpecialItemSupportCommonScope)

const finalItems = (disabledTypes: Array<string>) =>
  subCommonItems.map((it) => ({
    ...it,
    disabled: disabledTypes.includes(it.key)
  }))

const useHandleCreateSubItem = (subId: string, call: () => void) => {
  const { EditIndustryScope, openModal: openIndustry } = useEditIndustryScope()
  const { EditParkScope, openModal: openPark } = useEditParkScope()
  const { EditAreaScope, openModal: openArea } = useEditAreaScope()

  return {
    handleClick: (type: string, parentId = subId, selfId = '', oldValues: Array<{ name: string; value: string }> = [], callUpdate = call) => {
      if (!parentId) {
        message.error('没有parentId')
        return
      }
      switch (type) {
        case 'area':
          openArea(parentId, selfId, oldValues, callUpdate)
          break
        case 'industry':
          openIndustry(parentId, selfId, oldValues, callUpdate)
          break
        case 'park':
          openPark(parentId, selfId, oldValues, callUpdate)
          break
        default:
          throw '未知类型'
      }
    },
    Components: (
      <>
        {EditIndustryScope}
        {EditParkScope}
        {EditAreaScope}
      </>
    )
  }
}

export const useChooseCommonScopeType = () => {
  const [open, setOpen] = useState(false)

  const [subScopeId, setSubScopeId] = useState('')

  const callFn = useRef(() => {
    console.log('更新')
  })

  const { handleClick, Components } = useHandleCreateSubItem(subScopeId, callFn.current)

  return {
    Component: (
      <>
        <Modal
          {...commonModalStyle}
          open={open}
          title="选择范围类型"
          footer={null}
          onCancel={() => {
            setOpen(false)
          }}>
          <Menu
            selectedKeys={[]}
            items={finalItems([])}
            onClick={(item) => {
              handleClick(item.key)
              setOpen(false)
            }}
          />
        </Modal>
        {Components}
      </>
    ),
    openModal: useCallback((subId: string, call: () => void) => {
      setOpen(true)
      callFn.current = call
      setSubScopeId(subId)
    }, [])
  }
}

const ScopeCard = (props: {
  callUpdate: () => void
  scopeInfo: {
    id: string
    name: string
    draft: boolean
    type: 'specification' | 'company-white-list' | ''
    white_list_token: string
  }
}) => {
  const { scopeInfo } = props

  const editable = scopeInfo.draft

  const [subScopeList, setSubScopeList] = useState<
    Array<{
      id: string
    }>
  >([])

  const [scopeDetails, setScopeDetails] = useState<
    Record<
      string,
      Array<{
        id: string
        label: string
        type: string
        content: string
        values: Array<{
          name: string
          value: string
        }>
      }>
    >
  >({})

  const updateAll = () => {
    getSubCommonScopeList({
      scope_id: scopeInfo.id,
      page_size: 100,
      page: 1
    }).then((res) => {
      setSubScopeList(res.items)
    })
  }

  const updateScopeLine = (lineId: string) => {
    getScopeDetailList(lineId).then((res) => {
      const items =
        res.items?.map((it) => ({
          id: it.id,
          label: commonKinds.find((that) => that.key === it.type)?.label ?? '--',
          type: it.type,
          content: it.values?.map((itt) => itt.name)?.join('、') ?? '--',
          values: it.values
        })) ?? []
      setScopeDetails((prevState) => ({
        ...prevState,
        [lineId]: items
      }))
    })
  }

  const { handleClick, Components } = useHandleCreateSubItem('', updateAll)

  useEffect(() => {
    if (!scopeInfo.id) return
    getSubCommonScopeList({
      scope_id: scopeInfo.id,
      page_size: 100,
      page: 1
    }).then((res) => {
      setSubScopeList(res.items)
    })
  }, [scopeInfo])

  useEffect(() => {
    subScopeList.forEach((item) => {
      getScopeDetailList(item.id).then((res) => {
        const items =
          res.items?.map((it) => ({
            id: it.id,
            label: commonKinds.find((that) => that.key === it.type)?.label ?? '--',
            type: it.type,
            content: it.values?.map((itt) => itt.name)?.join('、') ?? '--',
            values: it.values
          })) ?? []
        setScopeDetails((prevState) => ({
          ...prevState,
          [item.id]: items
        }))
      })
    })
  }, [subScopeList])

  const doNewScope = (type: SubType, subId: string) => {
    handleClick(type, subId, '', [], () => {
      updateScopeLine(subId)
    })
  }

  return (
    <div className="flex flex-col gap-4">
      {subScopeList.map((first, fIndex) => (
        <Fragment key={first.id}>
          <div key={first.id} className="flex items-center">
            {editable && (
              <Popconfirm
                title={`确认删除范围${fIndex + 1}的所有范围？`}
                onConfirm={() => {
                  deleteSubCommonScopeList(first.id).then(() => {
                    getSubCommonScopeList({
                      scope_id: scopeInfo.id,
                      page_size: 100,
                      page: 1
                    }).then((res) => {
                      setSubScopeList(res.items)
                    })
                  })
                }}>
                <Button type="link">
                  <MinusCircleTwoTone className="text-2xl" />
                </Button>
              </Popconfirm>
            )}
            <div className="text-2xl font-bold whitespace-nowrap">范围{fIndex + 1}</div>
            <div className="flex flex-wrap gap-4 pl-4 items-center">
              {scopeDetails[first.id]?.map((it, index) => (
                <Fragment key={it.id}>
                  <div className="max-w-sm rounded overflow-hidden shadow-md p-2 relative bg-gray-200:40">
                    {editable && (
                      <>
                        <div className="flex items-center absolute right-0 top-0 p-1 text-xl gap-2">
                          <Popconfirm
                            title="确认删除？"
                            onConfirm={() => {
                              deleteScopeDetailItem(it.id).then(() => {
                                getScopeDetailList(first.id).then((res) => {
                                  const items =
                                    res.items?.map((it) => ({
                                      id: it.id,
                                      label: commonKinds.find((that) => that.key === it.type)?.label ?? '--',
                                      type: it.type,
                                      content: it.values?.map((itt) => itt.name)?.join('、') ?? '--',
                                      values: it.values
                                    })) ?? []
                                  setScopeDetails((prevState) => ({
                                    ...prevState,
                                    [first.id]: items
                                  }))
                                })
                              })
                            }}>
                            <MinusCircleTwoTone className="hover:cursor-pointer" />
                          </Popconfirm>
                        </div>
                        <div className="text-xl font-bold flex justify-between pr-12 items-center">
                          <span>{it.label}</span>
                          <Button
                            type="link"
                            onClick={() => {
                              handleClick(it.type, first.id, it.id, it.values, () => updateScopeLine(first.id))
                            }}>
                            去编辑
                          </Button>
                        </div>
                      </>
                    )}
                    <Paragraph
                      ellipsis={{
                        rows: 2,
                        expandable: true,
                        symbol: '展开'
                      }}>
                      {it.content}
                    </Paragraph>
                  </div>
                  {index != scopeDetails[first.id]?.length - 1 && (
                    <span className="font-bold bg-gray-200 rounded-full w-2em h-2em flex items-center justify-center">且</span>
                  )}
                </Fragment>
              ))}
              <Dropdown
                menu={{
                  items: finalItems(scopeDetails[first.id]?.map((it) => it.type) ?? []),
                  onClick: (item) => {
                    doNewScope(item.key as SubType, first.id)
                  }
                }}>
                <Button type="primary" ghost size="small">
                  添加
                </Button>
              </Dropdown>
            </div>
          </div>
          {fIndex != subScopeList.length - 1 && (
            <span className="font-bold bg-gray-200 rounded-full w-2em h-2em flex items-center justify-center ml-10">或</span>
          )}
        </Fragment>
      ))}
      {Components}
    </div>
  )
}

export default ScopeCard
